package com.webmagic;

import com.webmagic.entity.News;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;

public class MysqlPipeline implements Pipeline {


    public MysqlPipeline() {
    }

    @Override
    public void process(ResultItems resultitems, Task task) {
        Map<String, Object> mapResults = resultitems.getAll();
        Iterator<Map.Entry<String, Object>> iter = mapResults.entrySet().iterator();
        Map.Entry<String, Object> entry;
        // 输出到控制台
        while (iter.hasNext()) {
            entry = iter.next();
            System.out.println(entry.getKey() + "：" + entry.getValue());
        }
        // 持久化
        if(null!=mapResults&&mapResults.size()>0){
            News news = new News();
            if (!mapResults.get("Title").equals("")) {
                news.setTitle((String) mapResults.get("Title"));
                news.setContent((String) mapResults.get("Content"));
            }
            try {
                InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
                SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
                SqlSession session = sessionFactory.openSession();
                session.insert("add", news);
                session.commit();
                session.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
